/**
 * API接口管理
 * 封装所有后台管理系统的接口调用
 */

const request = require('./request.js')

/**
 * 用户认证相关API
 */
const auth = {
  /**
   * 微信登录
   * @param {Object} data - 登录数据 {code, encryptedData, iv}
   */
  login(data) {
    return request.post('/miniprogram/auth/login', data)
  },
  
  /**
   * 获取用户信息
   */
  getUserInfo() {
    return request.get('/miniprogram/user/info')
  },
  
  /**
   * 更新用户信息
   * @param {Object} data - 用户信息
   */
  updateUserInfo(data) {
    return request.put('/miniprogram/user/update', data)
  },
  
  /**
   * 绑定用户身份信息
   * @param {Object} data - 身份信息 {realName, idCard, studentNo, schoolId, classId}
   */
  bindUserIdentity(data) {
    return request.post('/miniprogram/user/bind', data)
  }
}

/**
 * 报警相关API
 */
const alarm = {
  /**
   * 提交报警信息
   * @param {Object} data - 报警数据
   */
  submit(data) {
    return request.post('/miniprogram/alarm/submit', data)
  },
  
  /**
   * 上传单个文件
   * @param {String} filePath - 文件路径
   * @param {Object} formData - 表单数据
   */
  uploadFile(filePath, formData = {}) {
    return request.upload('/miniprogram/alarm/upload', filePath, formData)
  },
  
  /**
   * 批量上传文件
   * @param {Array} files - 文件列表 [{filePath, type, name}]
   * @param {Object} formData - 表单数据
   */
  async uploadBatch(files, formData = {}) {
    const uploadPromises = files.map(file => {
      return request.upload('/miniprogram/alarm/upload', file.filePath, {
        ...formData,
        fileType: file.type,
        fileName: file.name
      })
    })
    
    try {
      const results = await Promise.all(uploadPromises)
      return {
        code: 200,
        message: '批量上传成功',
        data: results
      }
    } catch (error) {
      console.error('批量上传失败:', error)
      throw error
    }
  },
  
  /**
   * 查询报警历史
   * @param {Object} params - 查询参数 {pageNum, pageSize, startTime, endTime, type, status}
   */
  getHistory(params = {}) {
    return request.get('/miniprogram/alarm/history', params)
  },
  
  /**
   * 获取报警详情
   * @param {String} id - 报警ID
   */
  getDetail(id) {
    return request.get(`/miniprogram/alarm/detail/${id}`)
  },
  
  /**
   * 取消报警
   * @param {Object} data - 取消数据 {alarmId, reason}
   */
  cancel(data) {
    return request.post('/miniprogram/alarm/cancel', data)
  },
  
  /**
   * 获取报警状态
   * @param {String} id - 报警ID
   */
  getStatus(id) {
    return request.get(`/miniprogram/alarm/status/${id}`)
  },
  
  /**
   * 评价处理结果
   * @param {Object} data - 评价数据 {alarmId, rating, comment}
   */
  rate(data) {
    return request.post('/miniprogram/alarm/rate', data)
  },
  
  /**
   * 获取报警类型
   */
  getTypes() {
    return request.get('/miniprogram/alarm/types')
  },
  
  /**
   * 获取紧急联系方式
   * @param {String} schoolId - 学校ID
   */
  getEmergencyContact(schoolId) {
    return request.get(`/miniprogram/alarm/emergency/${schoolId}`)
  },
  
  /**
   * 检查提交权限
   * @param {Object} params - 检查参数 {userId, type}
   */
  checkSubmitPermission(params = {}) {
    return request.get('/miniprogram/alarm/checkSubmit', params)
  },
  
  /**
   * 获取用户统计数据
   * @param {Object} params - 查询参数 {userId, timeRange}
   */
  getStatistics(params = {}) {
    return request.get('/miniprogram/alarm/statistics', params)
  },
  
  /**
   * 获取WebSocket客户端ID
   */
  getWSClientId() {
    return request.get('/miniprogram/alarm/wsClientId')
  }
}

/**
 * 学校相关API
 */
const school = {
  /**
   * 获取学校列表
   * @param {Object} params - 查询参数 {keyword, region}
   */
  getList(params = {}) {
    return request.get('/miniprogram/school/list', params)
  },
  
  /**
   * 获取学校详情
   * @param {String} schoolId - 学校ID
   */
  getDetail(schoolId) {
    return request.get(`/miniprogram/school/detail/${schoolId}`)
  },
  
  /**
   * 获取班级列表
   * @param {String} schoolId - 学校ID
   * @param {Object} params - 查询参数 {grade}
   */
  getClasses(schoolId, params = {}) {
    return request.get(`/miniprogram/school/${schoolId}/classes`, params)
  }
}

/**
 * 设备相关API
 */
const device = {
  /**
   * 获取设备状态
   * @param {String} deviceId - 设备ID
   */
  getStatus(deviceId) {
    return request.get(`/miniprogram/device/status/${deviceId}`)
  },
  
  /**
   * 获取设备列表
   * @param {Object} params - 查询参数 {schoolId, area, type}
   */
  getList(params = {}) {
    return request.get('/miniprogram/device/list', params)
  },
  
  /**
   * 报告设备异常
   * @param {Object} data - 异常数据 {deviceId, type, description}
   */
  reportIssue(data) {
    return request.post('/miniprogram/device/report', data)
  }
}

/**
 * 消息通知相关API
 */
const notification = {
  /**
   * 获取消息列表
   * @param {Object} params - 查询参数 {pageNum, pageSize, type, status}
   */
  getList(params = {}) {
    return request.get('/miniprogram/notification/list', params)
  },
  
  /**
   * 标记消息已读
   * @param {String} id - 消息ID
   */
  markRead(id) {
    return request.put(`/miniprogram/notification/${id}/read`)
  },
  
  /**
   * 批量标记已读
   * @param {Array} ids - 消息ID数组
   */
  markBatchRead(ids) {
    return request.put('/miniprogram/notification/batchRead', { ids })
  },
  
  /**
   * 获取未读消息数量
   */
  getUnreadCount() {
    return request.get('/miniprogram/notification/unreadCount')
  }
}

/**
 * 系统配置相关API
 */
const config = {
  /**
   * 获取系统配置
   * @param {String} key - 配置键名
   */
  get(key) {
    return request.get(`/miniprogram/config/${key}`)
  },
  
  /**
   * 获取应用版本信息
   */
  getVersion() {
    return request.get('/miniprogram/config/version')
  },
  
  /**
   * 检查更新
   */
  checkUpdate() {
    return request.get('/miniprogram/config/checkUpdate')
  },
  
  /**
   * 获取服务条款
   */
  getTerms() {
    return request.get('/miniprogram/config/terms')
  },
  
  /**
   * 获取隐私政策
   */
  getPrivacy() {
    return request.get('/miniprogram/config/privacy')
  }
}

/**
 * WebSocket连接管理
 */
const websocket = {
  connection: null,
  clientId: null,
  callbacks: {
    onMessage: null,
    onClose: null,
    onError: null
  },
  
  /**
   * 连接WebSocket
   */
  async connect() {
    try {
      // 获取客户端ID
      const result = await alarm.getWSClientId()
      this.clientId = result.data.clientId
      
      // 建立WebSocket连接
      const wsUrl = `wss://your-backend-domain.com/ws/miniprogram/${this.clientId}`
      
      this.connection = wx.connectSocket({
        url: wsUrl,
        protocols: ['websocket']
      })
      
      // 监听连接打开
      this.connection.onOpen(() => {
        console.log('WebSocket连接已建立')
        
        // 发送认证信息
        this.send({
          type: 'auth',
          token: request.getToken()
        })
      })
      
      // 监听消息
      this.connection.onMessage((res) => {
        try {
          const message = JSON.parse(res.data)
          console.log('收到WebSocket消息:', message)
          
          if (this.callbacks.onMessage) {
            this.callbacks.onMessage(message)
          }
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
        }
      })
      
      // 监听连接关闭
      this.connection.onClose(() => {
        console.log('WebSocket连接已关闭')
        if (this.callbacks.onClose) {
          this.callbacks.onClose()
        }
      })
      
      // 监听连接错误
      this.connection.onError((error) => {
        console.error('WebSocket连接错误:', error)
        if (this.callbacks.onError) {
          this.callbacks.onError(error)
        }
      })
      
      return this.connection
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      throw error
    }
  },
  
  /**
   * 发送消息
   */
  send(data) {
    if (this.connection) {
      this.connection.send({
        data: JSON.stringify(data)
      })
    } else {
      console.warn('WebSocket未连接')
    }
  },
  
  /**
   * 关闭连接
   */
  close() {
    if (this.connection) {
      this.connection.close()
      this.connection = null
    }
  },
  
  /**
   * 设置回调函数
   */
  setCallbacks(callbacks) {
    this.callbacks = { ...this.callbacks, ...callbacks }
  }
}

// 导出API
module.exports = {
  auth,
  alarm,
  school,
  device,
  notification,
  config,
  websocket
} 